<?php
/**
 * Created by PhpStorm.
 * User: yy
 * Date: 2016/11/28
 * Time: 10:48
 */

namespace App\Services\Excel;

use App\Services\HelpService;

class ExcelReader
{
    private $__sheet;
    private $__column;
    private $__row;
    private $__pointer = 1;
    public $table_title = [];
    const A_ASCII = 65;

    public function __construct(string $file, array $title = []) {
        $obj_excel = \PHPExcel_IOFactory::createReader('Excel2007');
        $this->__sheet = $obj_excel->load($file)->getSheet(0);
        $this->__column = ord($this->__sheet->getHighestColumn());
        $this->__row = $this->__sheet->getHighestRow();
        if (empty($title)) {
            $this->getTableTitle();
        } else {
            $this->table_title = $title;
        }
    }

    public function readFile() {
        $content = [];
        do {
            $row = [];
            foreach ($this->table_title as $key => $title) {
                $value = $this->getValue($key);
                if (is_null($value)) {
                    continue 2;
                } else {
                    $row[$title] = $value;
                }
            }
            if (!empty($row)) {
                $row['index'] = $this->__pointer;
                $content[] = $row;
            }
        } while (++$this->__pointer <= $this->__row);
        return $content;
    }

    public function getTableTitle() {
        $column = self::A_ASCII;
        do {
            $cell = $this->getValue(chr($column));
            if (!is_null($cell)) {
                $this->table_title[chr($column)] = $cell;
            }
        } while (++$column <= $this->__column);
        ++$this->__pointer;
    }

    private function getValue($column) {
        return trim($this->__sheet
            ->getCell($column . $this->__pointer)
            ->getValue());
    }
}